<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${!dataId ? '新增' : '编辑'}-通知`"
		width="800px"
		append-to-body
		:confirm-btn-loading="confirmBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :show-message="false" label-width="110px" size="medium">
			<el-row>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="标题" prop="title">
						<el-input v-model="ruleForm.title" placeholder="标题" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="内容" prop="content">
						<el-input v-model="ruleForm.content" type="textarea" :rows="14" placeholder="内容" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="通知类型" prop="type">
						<jk-select v-model="ruleForm.type" :option-list="noticeTypeList" size="medium" placeholder="通知类型" class="width-100-percent"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="排序" prop="type">
						<jk-number-input v-model="ruleForm.sortNum" :option-list="noticeTypeList" size="medium" placeholder="排序" class="width-100-percent"></jk-number-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="通知主体" prop="noticeObjectId">
						<jk-select v-model="ruleForm.noticeObjectId" class="width-100-percent" size="medium" :option-list="noticeTargetCategoryList" placeholder="通知主体" @change="onNoticeRange"></jk-select>
					</el-form-item>
				</el-col>
				<el-col v-show="ruleForm.noticeObjectId !== 0" :span="24">
					<el-form-item v-if="ruleForm.noticeObjectId !== 0" class="margin-bottom-10" label="通知对象" prop="noticeBeCurrentList">
						<jk-select v-model="ruleForm.noticeBeCurrentList" multiple :multiple-limit="100" class="width-100-percent" size="medium" :option-list="targetList" placeholder="通知对象"></jk-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="生效时间" prop="expiringTime">
						<jk-date-picker v-model="ruleForm.expiringTime" size="medium" type="datetime" placeholder="生效时间"></jk-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="失效时间" prop="failureTime">
						<jk-date-picker v-model="ruleForm.failureTime" size="medium" type="datetime" placeholder="失效时间"></jk-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</jk-dialog>
</template>
<script>
    import { validateArr } from '../../../utils/jk/validator';
    import { formatTime, tipsBar } from '../../../utils/jk/jk-tool';
    import { systemNoticeCreate, systemNoticeGet, systemNoticeUpdate } from '../../../api/system/notice';
    import { noticeTargetCategoryList, noticeTypeList } from '../../../utils/jk/status-option-list';
    import { personnelGroupPage } from '../../../api/personnel/group';

    export default {
        props: {
            dataId: {
                type: [String, Number],
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                confirmBtnLoading: false,
                noticeTypeList: noticeTypeList,
                noticeTargetCategoryList: noticeTargetCategoryList,
                targetList: [],
                workshopList: [],
                groupList: [],
                showDialog: false,
                ruleForm: {
                    'content': '',
                    'expiringTime': '',
                    'failureTime': '',
                    'ifTopped': false,
                    'noticeBeCurrentList': [],
                    'noticeObjectId': 0,
                    'sortNum': 1,
                    'title': '',
                    'type': 0
                },
                rules: {
                    noticeBeCurrentList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    content: [{ required: true, trigger: 'change' }],
                    noticeObjectId: [{ required: true, trigger: 'change' }],
                    expiringTime: [{ required: true, trigger: 'change' }],
                    failureTime: [{ required: true, trigger: 'change' }],
                    title: [{ required: true, trigger: 'change' }],
                    type: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onNoticeRange() {
                this.$set(this.ruleForm, 'noticeBeCurrentList', []);
                this.setOptionData();
            },
            setOptionData() {
                if (this.ruleForm.noticeObjectId === 0) {
                    this.targetList = [];
                } else if (this.ruleForm.noticeObjectId === 1) {
                    this.targetList = JSON.parse(JSON.stringify(this.workshopList));
                } else if (this.ruleForm.noticeObjectId === 2) {
                    this.targetList = JSON.parse(JSON.stringify(this.groupList));
                } else if (this.ruleForm.noticeObjectId === 3) {
                    this.targetList = [];
                }
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const params = JSON.parse(JSON.stringify(this.ruleForm));
                        const api = !this.dataId ? systemNoticeCreate : systemNoticeUpdate;
                        if (!this.dataId) delete params.id;

                        if (params.noticeObjectId === 0) {
                            params.noticeBeCurrentList = [];
                        } else if (params.noticeObjectId === 1) {
                            params.noticeBeCurrentList = JSON.parse(JSON.stringify(this.workshopList)).filter(x => {
                                return params.noticeBeCurrentList.includes(x.id);
                            });
                        } else if (params.noticeObjectId === 2) {
                            params.noticeBeCurrentList = JSON.parse(JSON.stringify(this.groupList)).filter(x => {
                                return params.noticeBeCurrentList.includes(x.id);
                            });
                        }
                        this.confirmBtnLoading = true;
                        api(params).then(res => {
                            this.confirmBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$emit('on-confirm');
                                this.$tipsBar(this, 'save');
                            }
                        });
                    } else {
                        tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getGroupListRequest() {
                return personnelGroupPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res;
                    }
                });
            },
            getDetailRequest() {
                if (!this.dataId) return false;
                return systemNoticeGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.noticeBeCurrentList = resData.noticeBeCurrentList ? resData.noticeBeCurrentList.map(x => x.id) : [];
                        this.ruleForm = resData;
                        this.setOptionData();
                    }
                });
            },
            async getDependentData() {
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'expiringTime', formatTime(Date.now()));
                    this.$set(this.ruleForm, 'failureTime', formatTime(Date.now() + 7 * 24 * 60 * 60 * 1000));
                }
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                await this.getGroupListRequest();
                await this.getDetailRequest();
            }
        },
        watch: {
            dialogState(newVal) {
                if (newVal) {
                    this.getDependentData();
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                }
                this.showDialog = newVal;
            }
        }
    };
</script>
